<template>
  <a-spin :spinning="loading" size="large" tip="检测登录中...">
    <div class="login-page">
      <img src="@/assets/images/bg/titleR.png" alt="">
      <div class="login-title">
        Hello!
        <br>
        欢迎登录
        <br>
        智安系统
      </div>
      <div class="login-container">
        <p>账号</p>
        <van-field v-model="formData.idNum" placeholder="请输入手机号/用户名"
          :rules="[{ required: true, message: '请输入手机号/用户名' }]" />
        <p>密码</p>
        <van-field v-model="formData.password" :type="isPassword ? 'password' : ''" placeholder="请输入密码"
          :rules="[{ required: true, message: '请输入密码' }]">
          <template #button>
            <van-icon v-if="isPassword" name="closed-eye" @click="isPassword = !isPassword" />
            <van-icon v-else name="eye-o" @click="isPassword = !isPassword" />
          </template>
        </van-field>
        <div class="login-forgot" @click="forgotPassword">
          忘记密码
        </div>
        <div class="login-btn" @click="doSubmitTest">
          立即登录
        </div>
        <div class="login-btn pass" @click="doSubmitTest">
          免密登录
        </div>
        <div class="login-accord">
          我已阅读并同意的
          <font style="color: #2878FF;">《用户协议》</font>
          与
          <font style="color: #2878FF;">《隐私政策》</font>
        </div>
      </div>
    </div>
  </a-spin>
</template>
<script setup>
  import { reactive, inject, ref, onMounted } from "vue";
  import { getLogin, getSign, loginPhone } from "@/api/common.js";
  import router from "@/route/index.js";
  import { useRoute } from "vue-router";
  import { Icon as VanIcon } from "vant"
  const toast = inject("toast"),
    formData = reactive({
      idNum: "",
      password: ""
    }),
    route = useRoute(),
    loading = ref(false);
  const ddCorpId = ref("");// 公司corpId
  const isPassword = ref(true);

  function toHome() {
    if (!!route.query.redirect) {
      if(route.query.redirect == 'point-forms') {
        router.replace({
          path: `/${route.query.redirect}/${route.query.qrCode}?login=true`,
          query: {
            login: true
          }
        })
      } else {
        route.query.login = true
        router.replace({
          path: `/${route.query.redirect}`,
          query: route.query
        })        
      }
    } else if (!!route.query.windowId) {
      localStorage.setItem("WINDOW_ID", route.query.windowId)
      router.push('/windowAdd?login=true')
    } else {
      router.replace("/home")
    }
  }

  function doSubmitTest() {
    if (!formData.idNum) {
      return toast.msg("请输入登录账号！");
    }
    if (!formData.password) {
      return toast.msg("请输入登录密码！");
    }
    loading.value = true;
    let obj = {
      userName: formData.idNum,
      password: (formData.password)
    }
    loginPhone(obj).then(res => {
      if (res.code == 200) {
        localStorage.setItem("SAVE_TOKEN", res.data.sysToken)
        localStorage.setItem("SAVE_USER_INFO", JSON.stringify(res.data))
        localStorage.setItem("SAVE_USER_ACCOUNT", JSON.stringify(obj))
        toast.msg('登录成功！')
        loading.value = false;
        toHome()
      } else {
        toast.msg(res.message)
        loading.value = false
      }
    }, err => {
      toast.error(err.message)
      loading.value = false;
    })
  }

  onMounted(() => {
    let account = JSON.parse(localStorage.getItem("SAVE_USER_ACCOUNT"));
    if(!!account && account.userName && account.password) {
      formData.idNum = account.userName
      formData.password = account.password      
    }
    ddCorpId.value = route.query.corpId
    localStorage.setItem("CORPID_VAL", ddCorpId.value)
    // 钉钉免登
    let obj = {
      corpId: ddCorpId.value,
      signUrl: location.href.split("#")[0]
    }
    getSign(obj).then(res => {
      loading.value = true
      let userAgentStr = window.navigator.userAgent;
      if (!/DingTalk/.test(userAgentStr)) {
        loading.value = false
      }
      dd.config({
        appId: res.data.agentId, // 必填，微应用ID
        corpId: ddCorpId.value,//必填，企业ID
        timeStamp: Date.now(), // 必填，生成签名的时间戳
        nonceStr: res.data.nonceStr || 'jgkj', // 必填，自定义固定字符串。
        signature: res.data.sign, // 必填，签名
        jsApiList: [] // 必填，需要使用的jsapi列表，注意：不要带dd。
      });
      dd.error(function (err) {
        loading.value = false
        alert('dd error: ' + JSON.stringify(err));
      })

      dd.ready(function () {

        localStorage.setItem("corpId", ddCorpId.value)

        dd.runtime.permission.requestAuthCode({
          corpId: ddCorpId.value,
          onSuccess: function (result) {
            var code = result.code
            let obj = {
              code: code,
              corpId: ddCorpId.value
            }
            getLogin(obj).then(res => {
              localStorage.setItem("SAVE_TOKEN", res.data.sysToken)
              localStorage.setItem("SAVE_USER_INFO", JSON.stringify(res.data))
              if (!!route.query.type && route.query.type == 'exit') {
                // 退出状态下取消免登
                loading.value = false;
              } else {
                toHome()
              }
            }, err => {
              loading.value = false
              toast.msg(JSON.stringify(err))
            })
          },
          onFail: function (err) {
            loading.value = false;
          }
        })
      })
    }, err => {
      toast.msg('错误信息：' + JSON.stringify(err))
    })
  })

  function forgotPassword() {
    toast.msg('请联系管理员咨询！')
  }

</script>
<style lang="less">
  @import url("../../assets/style/login.less");
</style>